//
//  UserInfoViewController.m
//  AAIM
//
//  Created by 远的小布丁 on 2019/11/27.
//  Copyright © 2019 AAIM. All rights reserved.
//

#import "UserInfoViewController.h"
#import "UserInfoFirstTableViewCell.h"
#import "UserInfoTwoTableViewCell.h"
#import "ChangeNickNameViewController.h"
#import "NSObject+MJKeyValue.h"
#import "ProvinceCityModel.h"
#import <YYKit/YYKit.h>
#import "BRPickerViewMacro.h"
#import "BRMutableDatePickerView.h"
#import "FriendInfoTableViewCell.h"

@interface UserInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate, UIPickerViewDataSource,UIGestureRecognizerDelegate,ChangeVCDelegate>
@property (nonatomic,copy)UITableView * userInfoTableView;
@property (nonatomic,strong) NSArray * sectionAry;
@property (nonatomic,strong) NSArray * titleAry;
@property (nonatomic,copy) UIPickerView * cityPickView;//所在地
@property (nonatomic,copy) BRMutableDatePickerView * datePickView;//日期选择
@property(nonatomic, copy) NSString *birthDate;

@property (nonatomic, strong) NSDate *selectDate;
/** 是否隐藏【月】，默认为 NO */
@property (nonatomic, assign) BOOL hiddenMonth;
/** 是否隐藏【日】，默认为 NO */
@property (nonatomic, assign) BOOL hiddenDay;

@property (nonatomic,copy) UIView * backeView;//pickview背景view
@property (nonatomic,copy) UIButton * cancleBtn;
@property (nonatomic,copy) UIButton * sureBtn;
@property (nonatomic,copy) UILabel * addressLabel;
@property (nonatomic,copy) UIView * maskView;//遮罩

@property (nonatomic,copy) NSString * provinceStr;//省份
@property (nonatomic,copy) NSString * cityStr;//城市

@property (nonatomic,copy) NSString * provinceCode;//省份
@property (nonatomic,copy) NSString * cityCode;//城市

@property (nonatomic,copy) NSString * nickNameStr;
@property (nonatomic,copy) NSString * remarkStr;//签名
@property (nonatomic,copy) NSString * sexStr;
@property (nonatomic,copy) NSString * companyStr;
@property (nonatomic,copy) NSString * jobStr;

@property (nonatomic,assign) BOOL isDate;//判断点击哪个pickView
/**
 * plist对应的字典
 */
@property (nonatomic, strong) NSMutableArray* cityNames;
/**
 * 省份
 */
@property (nonatomic, strong) NSMutableArray* provinces;
/**
 * 城市
 */
@property (nonatomic, strong) NSArray* cities;

//手势
@property (nonatomic,strong) UITapGestureRecognizer * addressTap;
@property (nonatomic,strong) UITapGestureRecognizer * dateTap;
@property (nonatomic,strong) UserModel * model;
@property (nonatomic,strong) UserModel * dataModel;
@property (nonatomic,strong) NSMutableDictionary * dataDic;
@property (nonatomic,strong) NSMutableArray * citysArr;
@property (nonatomic,copy)NSString * contentStr;

@property (nonatomic,assign) BOOL isSave;//是否保存

@end

@implementation UserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"个人资料";
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.userInfoTableView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _isSave = YES;
    _model = [LoginManager shareLoginManager].userModel;
    
    //获取本地省市列表
    //先判断本地是否存在数据字典，存在则直接获取，不存在则请求后台数据
    if ([self getPlistDictionary]) {
        
        NSArray * dataAry = [self dictionaryWithJsonString:[self getPlistDictionary][@"province"]];
        //        NSLog(@"----------------%@",dataAry);
        [self.cityNames addObjectsFromArray:dataAry];
        
    }else{
        [self getProvinceAndCityData];
    }
    
    
    
    if (_index == 0) {
        
//        // 导航右按钮
        
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
       [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
        [rightBtn addTarget:self action:@selector(saveClick:) forControlEvents:UIControlEventTouchUpInside];
        [rightBtn sizeToFit];
        [rightBtn setBackgroundColor:KHEXCOLOR(kMainColor)];
        rightBtn.frame = CGRectMake(0, 0, 40, 25);
        rightBtn.layer.cornerRadius = 2;
        rightBtn.layer.masksToBounds = YES;
        rightBtn.titleLabel.font = kMainFont(12);
        rightBtn.jk_touchAreaInsets  = UIEdgeInsetsMake(20, 20, 20, 20);
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
        self.gk_navRightBarButtonItems = @[rightItem];
        
       UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
       [backBtn addTarget:self action:@selector(popClick:) forControlEvents:UIControlEventTouchUpInside];
       [backBtn sizeToFit];
        [backBtn setImage:[UIImage imageNamed:@"bar_back1"] forState:UIControlStateNormal];
       backBtn.frame = CGRectMake(0, 0, 40, 25);
       backBtn.jk_touchAreaInsets  = UIEdgeInsetsMake(20, 20, 20, 20);
       UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
       self.gk_navLeftBarButtonItems = @[backItem];
        
    }
    
    _sectionAry = @[@[@"基本信息"],@[@"个人资料"]];
    if (_index == 1) {
       _titleAry = @[@[@"",@"昵称",@"ID",@"签名",@"二维码"],@[@"",@"性别",@"生日",@"所在地",@"公司/机构",@"职业"]];
    }else{
         _titleAry = @[@[@"",@"昵称",@"账号",@"ID",@"签名",@"二维码"],@[@"",@"性别",@"生日",@"所在地",@"公司/机构",@"职业"]];
    }
   
    [self.view addSubview:self.backeView];
    [[[UIApplication sharedApplication] keyWindow]addSubview:self.maskView];
//    [self.view addSubview:self.maskView];
    
    
    _addressTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showAddressPickView)];
    
    _addressTap.numberOfTapsRequired = 1;
    _addressTap.numberOfTouchesRequired = 1;
    
    _dateTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showDatePickView)];
    
    _dateTap.numberOfTapsRequired = 1;
    _dateTap.numberOfTouchesRequired = 1;
    
    _backeView.hidden = YES;
    _maskView.hidden = YES;
    
    [self.backeView addSubview:self.datePickView];
    [self.backeView addSubview:self.cityPickView];
    [self setMasorny];
    
    _dataDic = [NSMutableDictionary dictionary];
    
    [self getUserInfo];
}
- (void)popClick:(UIButton *)sender{
    if (_isSave) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        UIAlertController * alerVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您有新的修改未保存，确定退出？" preferredStyle:UIAlertControllerStyleAlert];
        UIView * subview = alerVC.view.subviews.firstObject;
        UIView * alertContentView = subview.subviews.firstObject;
        alertContentView.backgroundColor = [UIColor whiteColor];
        alertContentView.layer.cornerRadius = 15;
        
        
        UIAlertAction * sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [sure setValue:KHEXCOLOR(@"#262B2F") forKey:@"titleTextColor"];
        UIAlertAction * cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [cancle setValue:KHEXCOLOR(@"#AFAFAF") forKey:@"titleTextColor"];
        
        [alerVC addAction:cancle];
        [alerVC addAction:sure];
        [self.navigationController presentViewController:alerVC animated:YES completion:nil];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.gk_navigationBar.gk_navLineHidden = NO;
     
}

- (NSArray *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    //    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    NSArray * ary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err)
    {
        //        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    
    
    
    for (NSDictionary * provDic in ary) {
        if (provDic[@"name"]) {
            [self.provinces addObject:@{provDic[@"code"]:provDic[@"name"]}];
            
        }
        for (NSDictionary * cityD in provDic[@"citys"]) {
            [self.citysArr addObject:@{cityD[@"code"]:cityD[@"name"]}];
        }
    }
    
    return ary;
}

- (void)getProvinceAndCityData{
    [RequestData GetProvincesAndCitiesWithToken:self.model.token userUUid:self.model.fuuid Success:^(NSDictionary * _Nonnull Dict) {
        KWeakSelf;
        weakSelf.cityNames = Dict[@"data"];
        //        NSLog(@"省份%@",Dict);
        for (NSDictionary * provDic in Dict[@"data"]) {
            if (provDic[@"name"]) {
                [weakSelf.provinces addObject:@{[NSString stringWithFormat:@"%@",provDic[@"code"]]:provDic[@"name"]}];
                
            }
            for (NSDictionary * cityD in provDic[@"citys"]) {
                [weakSelf.citysArr addObject:@{[NSString stringWithFormat:@"%@",cityD[@"code"]]:cityD[@"name"]}];
            }
        }
        
        [weakSelf.cityPickView reloadAllComponents];
        NSString * jsonStr = [self convertToJsonData:Dict[@"data"]];
        
        NSMutableDictionary * dic =[NSMutableDictionary new];
        [dic setValue:jsonStr forKey:@"province"];
        [CacheTool savePlist:@"ProvinceCity.plist" dataObj:dic];
        
        NSString *savepath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSLog(@"沙盒地址===%@", savepath);
        
    } failure:^(NSString * _Nonnull errMsg) {
        NSLog(@"请求失败了:%@",errMsg);
    }];
}

-(NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}


//读取plist（代码创建的plist文件）

- (NSDictionary *)getPlistDictionary

{
    NSDictionary * provinceCityDict=[CacheTool readPlist:@"ProvinceCity.plist" dataClass:NSMutableDictionary.class];
    
    return provinceCityDict;
}

- (void)changeUserInfo{
    
    if (!_birthDate) {
        _birthDate = _model.birthdate;
    }
    KWeakSelf;
    [RequestData changeUserInfoWithToken:_model.token userUUid:_model.uuid areaStr:@"" withBirthday:_birthDate withCity:_cityCode withCompany:_companyStr withHead:@"" withIsVerify:@"" withJob:_jobStr withNickName:_nickNameStr withProvince:_provinceCode withRemark:_remarkStr withSex:_sexStr Success:^(NSDictionary * _Nonnull Dict) {
        weakSelf.isSave = YES;
        [self showTipHudWithText:@"保存成功"];
        if (self.delegate) {
            [self.delegate changeUserInfoDisPlay];
        }
        [self getUserInfo];
    } failure:^(NSString * _Nonnull errMsg) {
        NSLog(@"修改信息失败%@",errMsg);
        weakSelf.isSave = NO;
        [self showTipHudWithText:@"保存失败"];
    }];
    
    
}


- (void)getUserInfo{
    
    if (_index == 0) {
        
        [RequestData GetUserInfoWithToken:self.model.token userUUid:self.model.uuid fuuid:_model.fuuid Success:^(NSDictionary * _Nonnull Dict) {
            NSLog(@"个人信息：%@",Dict);
            KWeakSelf;
            if ([Dict[@"code"] integerValue] == 200) {
                UserModel * newModel = [LoginManager shareLoginManager].userModel;
                weakSelf.dataDic = Dict[@"data"];
                weakSelf.dataModel = [UserModel mj_objectWithKeyValues:weakSelf.dataDic];
                //时间戳转字符串
                if (![Dict[@"data"][@"birthday"] isKindOfClass:[NSNull class]]) {
                    NSString * date = [NSDate dateStrFromCstampTime:[Dict[@"data"][@"birthday"] integerValue] withDateFormat:@"yyyy-MM-dd"];
                    if (![date isEqualToString:weakSelf.model.birthdate]){
                        weakSelf.model.birthdate = date;
                        weakSelf.dataModel.birthdate = date;
                        newModel.birthdate = date;
                    }
                }
                NSString * sex = [NSString stringWithFormat:@"%@",Dict[@"data"][@"sex"]];
                if (![sex isEqualToString:weakSelf.model.sex]) {
                    weakSelf.model.birthdate = Dict[@"data"][@"sex"];
                    newModel.birthdate = Dict[@"data"][@"sex"];
                }else if (![Dict[@"data"][@"nickname"]isEqualToString:weakSelf.model.nickname]){
                    weakSelf.model.nickname = Dict[@"data"][@"nickname"];
                    newModel.nickname = Dict[@"data"][@"nickname"];
                }
                weakSelf.model.describe = Dict[@"data"][@"describe"];
                newModel.describe = Dict[@"data"][@"describe"];
                for (NSDictionary * proDi in weakSelf.cityNames) {
                    if (Dict[@"data"][@"province"] == proDi[@"code"]) {
                        NSLog(@"%@----%@",Dict[@"data"][@"province"],proDi[@"code"]);
                        weakSelf.model.province = proDi[@"name"];
                        newModel.province = proDi[@"name"];
                        weakSelf.dataModel.province = proDi[@"name"];
                        for (NSDictionary * cityD in proDi[@"citys"]) {
                            if (Dict[@"data"][@"city"] == cityD[@"code"]) {
                                weakSelf.dataModel.city = cityD[@"name"];
                                weakSelf.model.city = cityD[@"name"];
                                newModel.city = cityD[@"name"];
                            }
                        }
                    }
                }
                weakSelf.model.company = Dict[@"data"][@"company"];
                weakSelf.model.job = Dict[@"data"][@"job"];
                
                newModel.company = Dict[@"data"][@"company"];
                newModel.job = Dict[@"data"][@"job"];
                [[LoginManager shareLoginManager] saveLoginCustomer:newModel];
                [self.userInfoTableView reloadData];
            }
        } failure:^(NSString * _Nonnull errMsg) {
            //        NSLog(@"出错了：%@",errMsg);
            [self showTipHudWithText:@"网络异常，稍后再试"];
        }];
    }else{
        
        [RequestData GetUserInfoWithToken:self.model.token userUUid:self.model.uuid fuuid:self.fuuid Success:^(NSDictionary * _Nonnull Dict) {
            NSLog(@"个人信息：%@",Dict);
            KWeakSelf;
            if ([Dict[@"code"] integerValue] == 200) {
                weakSelf.dataDic = Dict[@"data"];
                weakSelf.dataModel = [UserModel mj_objectWithKeyValues:weakSelf.dataDic];
                //时间戳转字符串
                if (![Dict[@"data"][@"birthday"] isKindOfClass:[NSNull class]]) {
                    NSString * date = [NSDate dateStrFromCstampTime:[Dict[@"data"][@"birthday"] integerValue] withDateFormat:@"yyyy-MM-dd"];
                    if (![date isEqualToString:weakSelf.model.birthdate]){
                        weakSelf.model.birthdate = date;
                        weakSelf.dataModel.birthdate = date;
                    }
                }
                
                for (NSDictionary * proDi in weakSelf.cityNames) {
                    
                    if (Dict[@"data"][@"province"] == proDi[@"code"]) {
                        weakSelf.dataModel.province = proDi[@"name"];
                    }
                    for (NSDictionary * cityD in proDi[@"citys"]) {
                        if (Dict[@"data"][@"city"] == cityD[@"code"]) {
                            weakSelf.dataModel.city = cityD[@"name"];
                        }
                    }
                    
                }
                
                [self.userInfoTableView reloadData];
            }
        } failure:^(NSString * _Nonnull errMsg) {
            //        NSLog(@"出错了：%@",errMsg);
            [self showTipHudWithText:@"网络异常，稍后再试"];
        }];
    }
}

- (void)setMasorny{
    [_backeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.view.mas_bottom);
        make.height.offset(288.f);
        make.right.equalTo(self.view.mas_right);
    }];
//    [_maskView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view.mas_top);
//        make.left.equalTo(self.view.mas_left);
//        make.right.equalTo(self.view.mas_right);
//        make.bottom.equalTo(self.backeView.mas_top);
//    }];
    
    UIView * btnBackView = [UIView new];
    btnBackView.backgroundColor = KHEXCOLOR(@"#FFFFFF");
    [self.backeView addSubview:btnBackView];
    UIView * line = [UIView new];
    [btnBackView addSubview:line];
    line.backgroundColor = KHEXCOLOR(@"e0e0e0");
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(btnBackView.mas_left);
        make.right.equalTo(btnBackView.mas_right);
        make.bottom.equalTo(btnBackView.mas_bottom);
        make.height.offset(0.5f);
    }];
    [btnBackView addSubview:self.cancleBtn];
    [btnBackView addSubview:self.addressLabel];
    [btnBackView addSubview:self.sureBtn];
    [btnBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.backeView.mas_left);
        make.right.equalTo(self.backeView.mas_right);
        make.top.equalTo(self.backeView.mas_top);
        make.height.offset(45.f);
    }];
    [_cancleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(btnBackView.mas_left);
        make.top.equalTo(btnBackView.mas_top);
        make.width.offset(SCALAE_WIDTH(45));
        make.bottom.equalTo(line.mas_top);
    }];
    
    [_sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(btnBackView.mas_right);
        make.top.equalTo(btnBackView.mas_top);
        make.width.offset(SCALAE_WIDTH(45));
        make.bottom.equalTo(line.mas_top);
    }];
    
    [_addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.cancleBtn.mas_right);
        make.right.equalTo(self.sureBtn.mas_left);
        make.top.equalTo(btnBackView.mas_top);
        make.bottom.equalTo(btnBackView.mas_bottom);
    }];
    
    [_cityPickView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.backeView.mas_left);
        make.bottom.equalTo(self.backeView.mas_bottom);
        make.right.equalTo(self.backeView.mas_right);
        make.top.equalTo(btnBackView.mas_bottom);
    }];
    
    [_datePickView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.backeView.mas_left);
        make.top.equalTo(btnBackView.mas_bottom);
        make.right.equalTo(self.backeView.mas_right);
        make.bottom.equalTo(self.backeView.mas_bottom);
    }];
    
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_titleAry[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        UserInfoFirstTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"UserFirstTableViewCell"];
        if (!cell) {
            
            cell = [[UserInfoFirstTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UserFirstTableViewCell"];
        }
        cell.sectionNameLabel.text = _sectionAry[indexPath.section][indexPath.row];
        return cell;
    }else{

        if (_index == 1) {
           FriendInfoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"FriendInfoTableViewCell"];

                  if (!cell) {
                      cell = [[FriendInfoTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FriendInfoTableViewCell"];
                  }
                  if (indexPath.row == 5) {
                      cell.line.hidden = YES;
                  }
                  if (indexPath.section == 0&& indexPath.row == 4) {
                      cell.isShow = 0;
                  }else{
                      cell.isShow = 1;
                  }
                  if (_index == 1 ) {
                      if (indexPath.section == 0 && indexPath.row == 4) {
                           cell.rightImageView.hidden = NO;
                      }else{
                          cell.rightImageView.hidden = YES;
                      }
                  }

                if (indexPath.section == 0) {
                      if (indexPath.row == 1) {
                          cell.nameLabel.text = _dataModel.nickname;
                      }else if (indexPath.row == 2){
                          cell.nameLabel.text = _dataModel.fuuid;
                      }
                      if (indexPath.row == 2) {
                         cell.rightImageView.hidden = YES;
                    }
                  }
                  NSString * str = _titleAry[indexPath.section][indexPath.row];
                  cell.str = str;

                  if (indexPath.section == 0 && indexPath.row == 3) {
                      if (_dataModel.remark) {
                          cell.nameLabel.text = _dataModel.remark;
                      }else{
                          if (_index == 1) {
                              cell.nameLabel.text =@"这个人很懒，什么都没留下";
                          }else{
                              cell.nameLabel.text =@"简单的介绍下自己";
                          }
                      }
                  }
                  if (indexPath.section == 1) {
                      if (indexPath.row == 1){
                          cell.nameLabel.userInteractionEnabled = YES;
                          if (_dataModel.sex) {
                              if ([_dataModel.sex isEqualToString:@"0"]) {
                                  cell.nameLabel.text = @"男";
                              }else{
                                  cell.nameLabel.text = @"女";
                              }
                          }else{
                              cell.nameLabel.text = @"";
                          }
                      } else if (indexPath.row == 2) {
                          if (_index != 1) {
                              cell.nameLabel.userInteractionEnabled = YES;
                              [cell.nameLabel addGestureRecognizer:_dateTap];
                          }

                          if (_birthDate) {
                              cell.nameLabel.text = _birthDate;
                          }else if (_dataModel.birthdate) {
                              cell.nameLabel.text = _dataModel.birthdate;
                          }else{
                              if (!_birthDate) {
                                  if (_index == 1) {
                                      cell.nameLabel.text =@"待完善资料";
                                  }else{
                                      cell.nameLabel.text =@"请完善资料";
                                  }
                              }else{
                                  cell.nameLabel.text = _birthDate;
                              }

                          }

                      }else if (indexPath.row == 3){
                          if (_index != 1) {
                              cell.nameLabel.userInteractionEnabled = YES;
                              [cell.nameLabel addGestureRecognizer:_addressTap];
                          }

                          if (!_provinceStr&&!_cityStr) {
                              if (_dataModel.province&&_dataModel.city) {
                                  cell.nameLabel.text = [NSString stringWithFormat:@"%@-%@",_dataModel.province,_dataModel.city];
                              }else{
                                  if (_index == 1) {
                                      cell.nameLabel.text =@"待完善资料";
                                  }else{
                                      cell.nameLabel.text =@"请完善资料";
                                  }
                              }

                          }else if (_provinceStr&&!_cityStr){
                              cell.nameLabel.text = [NSString stringWithFormat:@"%@-%@",_provinceStr,_cities[0]];
                          }else{
                              cell.nameLabel.text = [NSString stringWithFormat:@"%@-%@",_provinceStr,_cityStr];
                          }
                      }
                      else{
                          cell.nameLabel.userInteractionEnabled = NO;
                          if (indexPath.row == 4) {
                              if (_dataModel.company) {
                                  cell.nameLabel.text = _dataModel.company;
                              }else{
                                  if (_index == 1) {
                                      cell.nameLabel.text =@"待完善资料";
                                  }else{
                                      cell.nameLabel.text =@"请完善资料";
                                  }
                              }
                          }else{
                              if (_dataModel.job) {
                                  cell.nameLabel.text = _dataModel.job;
                              }else{
                                  if (_index == 1) {
                                      cell.nameLabel.text =@"待完善资料";
                                  }else{
                                      cell.nameLabel.text =@"请完善资料";
                                  }

                              }
                          }
                      }
                  }


                  return cell;
              }else{
          UserInfoTwoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoTwoTableViewCell"];
                  
                  if (!cell) {
                      cell = [[UserInfoTwoTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UserInfoTwoTableViewCell"];
                  }
                  if (indexPath.row == 5) {
                      cell.line.hidden = YES;
                  }
                  if (indexPath.section == 0&& indexPath.row == 5) {
                      cell.isShow = 0;
                  }else{
                      cell.isShow = 1;
                  }
                  if (_index == 1 ) {
                      if (indexPath.section == 0 && indexPath.row == 5) {
                     
                      cell.rightImageView.hidden = NO;
                      }else{
                          cell.rightImageView.hidden = YES;
                      }
                  }
                  
                  if (indexPath.section == 0) {
                      if (indexPath.row == 1) {
                          cell.nameLabel.text = _dataModel.nickname;
                      }else if (indexPath.row == 2){
                          cell.nameLabel.text = _dataModel.userName;
                      }else if (indexPath.row == 3){
                          cell.nameLabel.text = _dataModel.fuuid;
                      }
                      if (indexPath.row == 2 || indexPath.row == 3) {
                          cell.rightImageView.hidden = YES;
                      }
                  }
                  NSString * str = _titleAry[indexPath.section][indexPath.row];
                  cell.str = str;
                  
                  if (indexPath.section == 0 && indexPath.row == 4) {
                      if (_dataModel.remark) {
                          cell.nameLabel.text = _dataModel.remark;
                      }else{
                          if (_index == 1) {
                              cell.nameLabel.text =@"这个人很懒，什么都没留下";
                          }else{
                              cell.nameLabel.text =@"简单的介绍下自己";
                          }
                      }
                  }
                  if (indexPath.section == 1) {
                      if (indexPath.row == 1){
                          cell.nameLabel.userInteractionEnabled = YES;
                          if (_dataModel.sex) {
                              if ([_dataModel.sex isEqualToString:@"0"]) {
                                  cell.nameLabel.text = @"男";
                              }else{
                                  cell.nameLabel.text = @"女";
                              }
                          }else{
                              cell.nameLabel.text = @"";
                          }
                      } else if (indexPath.row == 2) {
                          if (_index != 1) {
                              cell.nameLabel.userInteractionEnabled = YES;
                              [cell.nameLabel addGestureRecognizer:_dateTap];
                          }
                          
                          if (_birthDate) {
                              cell.nameLabel.text = _birthDate;
                          }else if (_dataModel.birthdate) {
                              cell.nameLabel.text = _dataModel.birthdate;
                          }else{
                              if (!_birthDate) {
                                  if (_index == 1) {
                                      cell.nameLabel.text =@"待完善资料";
                                  }else{
                                      cell.nameLabel.text =@"请完善资料";
                                  }
                              }else{
                                  cell.nameLabel.text = _birthDate;
                              }
                              
                          }
                          
                      }else if (indexPath.row == 3){
                          if (_index != 1) {
                              cell.nameLabel.userInteractionEnabled = YES;
                              [cell.nameLabel addGestureRecognizer:_addressTap];
                          }
                          
                          if (!_provinceStr&&!_cityStr) {
                              if (_dataModel.province&&_dataModel.city) {
                                  cell.nameLabel.text = [NSString stringWithFormat:@"%@-%@",_dataModel.province,_dataModel.city];
                              }else{
                                  if (_index == 1) {
                                      cell.nameLabel.text =@"待完善资料";
                                  }else{
                                      cell.nameLabel.text =@"请完善资料";
                                  }
                              }
                              
                          }else if (_provinceStr&&!_cityStr){
                              cell.nameLabel.text = [NSString stringWithFormat:@"%@-%@",_provinceStr,_cities[0]];
                          }else{
                              cell.nameLabel.text = [NSString stringWithFormat:@"%@-%@",_provinceStr,_cityStr];
                          }
                      }
                      else{
                          cell.nameLabel.userInteractionEnabled = NO;
                          if (indexPath.row == 4) {
                              if (_dataModel.company) {
                                  cell.nameLabel.text = _dataModel.company;
                              }else{
                                  if (_index == 1) {
                                      cell.nameLabel.text =@"待完善资料";
                                  }else{
                                      cell.nameLabel.text =@"请完善资料";
                                  }
                              }
                          }else{
                              if (_dataModel.job) {
                                  cell.nameLabel.text = _dataModel.job;
                              }else{
                                  if (_index == 1) {
                                      cell.nameLabel.text =@"待完善资料";
                                  }else{
                                      cell.nameLabel.text =@"请完善资料";
                                  }
                                  
                              }
                          }
                      }
                  }
                  
                  
                  return cell;
              }
        
    }
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 8.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * headerView = [UIView new];
    headerView.backgroundColor = KHEXCOLOR(@"#F4F4F4");
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


    if (_index != 1) {
        UserInfoTwoTableViewCell * cell = [_userInfoTableView cellForRowAtIndexPath:indexPath];
        ChangeNickNameViewController * changeVC = [[ChangeNickNameViewController alloc]init];
        changeVC.delegate = self;
        changeVC.indexPath = indexPath;
        if (indexPath.row != 0 && indexPath.row != 2 && indexPath.row !=3 ) {
            if (![cell.nameLabel.text isEqualToString:@"请完善资料"]&&![cell.nameLabel.text isEqualToString:@"简单的介绍下自己"]) {
             changeVC.contentStr = cell.nameLabel.text;
            }
            if (indexPath.section == 0) {
                switch (indexPath.row) {
                    case 1:
                        changeVC.index = 1;
                        break;
                    case 4:
                        changeVC.index = 2;
                        break;
                    case 5:
                        changeVC.index = 3;
                        changeVC.qrCodeStr = _dataModel.qrCodeurl;
                        break;
                }
            }else{
                switch (indexPath.row) {
                    case 1:
                        changeVC.index = 4;
                        changeVC.sexIndex = _dataModel.sex;
                        break;
                    case 4:
                        changeVC.index = 5;
                        break;
                    case 5:
                        changeVC.index = 6;
                        break;
                        
                    default:
                        
                        break;
                }
            }
             [self.navigationController pushViewController:changeVC animated:YES];
        }
        
    }else{
        ChangeNickNameViewController * changeVC = [[ChangeNickNameViewController alloc]init];
        changeVC.delegate = self;
        changeVC.indexPath = indexPath;
        if (indexPath.section == 0 && indexPath.row == 4) {
            changeVC.index = 3;
            changeVC.qrCodeStr = _dataModel.qrCodeurl;
            changeVC.model = _dataModel;
            changeVC.pageType = @"friendInfo";
             [self.navigationController pushViewController:changeVC animated:YES];
        }
        
    }
    
}

- (void)changeWithStr:(NSString *)text withIndexPath:(nonnull NSIndexPath *)indexPath{
    NSLog(@"%@",text);
    //    UserInfoTwoTableViewCell * cell = [_userInfoTableView cellForRowAtIndexPath:indexPath];
    //    cell.nameLabel.text = text;
    _isSave = NO;
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 1:
                _dataModel.nickname = text;
                _nickNameStr = text;
                break;
                
            default:
                _dataModel.remark = text;
                _remarkStr = text;
                break;
        }
    }else{
        switch (indexPath.row) {
            case 1:
                _dataModel.sex = text;
                _sexStr = text;
                break;
            case 4:
                _dataModel.company = text;
                _companyStr = text;
                break;
            case 5:
                _dataModel.job = text;
                _jobStr = text;
                break;
                
            default:
                break;
        }
    }
    [self.userInfoTableView reloadData];
    
    
}

//保存
- (void)saveClick:(UIButton *)sender{
    NSLog(@"保存");
    [self changeUserInfo];
}

//取消选择器
- (void)cancleActive{
    NSLog(@"取消");
    _maskView.hidden = YES;
    _backeView.hidden = YES;
}

//确定选择
- (void)sureActive:(UIButton *)sender{
    NSLog(@"确定");
    _maskView.hidden = YES;
    _backeView.hidden = YES;
    if (!_isDate){
        if (!_provinceStr) {
            _provinceStr = self.cityNames[0][@"name"];
            _cityStr = self.cities[0][@"name"];
            
            _provinceCode = self.cityNames[0][@"code"];
            _cityCode = self.cities[0][@"code"];
            
        }else if (_provinceStr && !_cityStr){
            _cityStr = self.cities[0][@"name"];
            _cityCode = self.cities[0][@"code"];
        }
        _isSave = NO;
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:1];
        [_userInfoTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
    }else{
        _isSave = NO;
    }
}

- (void)showAddressPickView{
    _maskView.hidden = NO;
    _backeView.hidden = NO;
    _isDate = NO;
    _cityPickView.hidden = NO;
    _addressLabel.hidden = NO;
}

- (void)showDatePickView{
    _maskView.hidden = YES;
    _backeView.hidden = YES;
    _isDate = YES;
    _addressLabel.hidden = YES;
    _cityPickView.hidden = YES;
    _datePickView = [[BRMutableDatePickerView alloc]init];
    _datePickView.selectDate = self.selectDate;
    _datePickView.hiddenDateUnit = YES;
    _datePickView.hiddenMonth = self.hiddenMonth;
    _datePickView.hiddenDay = self.hiddenDay;
    KWeakSelf;
    _datePickView.resultBlock = ^(NSDate *selectDate, NSString *selectValue, BOOL hiddenMonth, BOOL hiddenDay) {
        NSLog(@"选择的时间：%@", selectValue);
        weakSelf.selectDate = selectDate;
        weakSelf.hiddenMonth = hiddenMonth;
        weakSelf.hiddenDay = hiddenDay;
        weakSelf.maskView.hidden = YES;
        weakSelf.birthDate = selectValue;
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:1];
        [weakSelf.userInfoTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        weakSelf.isSave = NO;
    };
    


    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *currentDate = [NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:0];//设置最大时间为：当前时间推后0年
    NSDate *maxDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
    [comps setYear:-100];//设置最小时间为：当前时间前推100年
    NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];

    _datePickView.maxDate = maxDate;
    _datePickView.minDate = minDate;
    [_datePickView show];
}

////监听日期选择器
//- (void)dateChanged
//{
//    NSDate *theDate;
//    __block NSDate * weakDate = theDate;
//    _datePickView.resultBlock = ^(NSDate *selectDate, NSString *selectValue, BOOL hiddenMonth, BOOL hiddenDay) {
//        weakDate = selectDate;
//    };
//
//    //    NSLog(@"%@",[theDate descriptionWithLocale:[NSLocale currentLocale]]);
//
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    dateFormatter.dateFormat = @"YYYY-MM-dd";
//    //    NSLog(@"%@",[dateFormatter stringFromDate:theDate]);
//    _dataModel.birthdate = [dateFormatter stringFromDate:weakDate];
//
//    _birthDate = [dateFormatter stringFromDate:weakDate];
//
//
//    // _birthDate = [NSDate dateFromString:[dateFormatter stringFromDate:theDate] format:@"YYYY-MM-dd"];
//
//}

//- (NSString *)chooseCurrentDate{
//    NSDate *theDate = [NSDate date];
//    //    NSLog(@"%@",[theDate descriptionWithLocale:[NSLocale currentLocale]]);
//    
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    dateFormatter.dateFormat = @"YYYY-MM-dd";
//    NSString *str = [dateFormatter stringFromDate:theDate];
//    return str;
//}

/**
 * 返回每一列的行数
 */
- (NSInteger)pickerView:(UIPickerView*)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    if (component == 0) {
        //        if (self.provinces.count == 0) {
        //            return 1;
        //        }
        return self.cityNames.count;
    }
    else {
        
        [self loadData:pickerView];
        //        self.cities = self.cityNames[0][@"cities"];
        if (self.cities.count <= 0) {
            return 1;
        }
//        NSLog(@"行数：%ld",self.cities.count);
        return self.cities.count;
    }
}

/**
 * 返回每一行显示的文本
 *
 *
 */
- (NSString*)pickerView:(UIPickerView*)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    //第一列返回所有的省份
    if (component == 0) {
        if (self.cityNames.count == 0) {
            return nil;
        }
        
        NSString * cr = self.cityNames[row][@"name"];
        return cr;
    }else {
        
        [self loadData:pickerView];
        if (self.cities.count <= row) {
            return nil;
        }
        
        return self.cities[row][@"name"];
        
    }
}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{

UILabel *lbl = (UILabel *)view;

if (lbl == nil) {

lbl = [[UILabel alloc]init];

//在这里设置字体相关属性

lbl.font = [UIFont systemFontOfSize:18];

lbl.textColor = KHEXCOLOR(@"#262B2F");

[lbl setTextAlignment:1];

[lbl setBackgroundColor:[UIColor clearColor]];

}

//重新加载lbl的文字内容

lbl.text = [self pickerView:pickerView titleForRow:row forComponent:component];

return lbl;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 44.f;
}

/**
 * 加载第二列显示的数据
 *
 */
-(void)loadData:(UIPickerView*)pickerView
{
    
    //一定要首先获取用户选择的那一行 然后才可以根据选中行获取省份 获取省份以后再去字典中加载省份对应的城市
    NSInteger selRow = [pickerView selectedRowInComponent:0];
    if (self.cityNames.count >0) {
        //            self.cities = [NSArray arrayWithObject:self.cityNames[selRow][@"citys"]];
        self.cities = self.cityNames[selRow][@"citys"];
    }
    
    
}

/**
 * 一共多少咧
 *
 */
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
    
    return 2;
}

/**
 * 选中某一行后回调 联动的关键
 *
 * @param row    用户选择的省份
 */
- (void)pickerView:(UIPickerView*)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if (component == 0) {
        
        //重新加载第二列的数据
        [pickerView reloadComponent:1];
        //让第二列归位
        [pickerView selectRow:0 inComponent:1 animated:YES];
        NSLog(@"选择的省份---%@",self.cityNames[row][@"name"]);
        _provinceStr = self.cityNames[row][@"name"];
        _provinceCode = self.cityNames[row][@"code"];
    }else{
        _cityStr = self.cities[row][@"name"];
        _cityCode = self.cities[row][@"code"];
    }
    
}


- (UITableView *)userInfoTableView{
    if (!_userInfoTableView) {
        _userInfoTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.gk_navigationBar.bottom, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
        _userInfoTableView.delegate = self;
        _userInfoTableView.dataSource = self;
        _userInfoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 1.f)];
        
        headerView.backgroundColor = KHEXCOLOR(@"#F4F4F4");
        _userInfoTableView.tableHeaderView = headerView;
        _userInfoTableView.tableFooterView = [UIView new];
        _userInfoTableView.backgroundColor = KHEXCOLOR(@"#F4F4F4");
    }
    return _userInfoTableView;
}

- (UIView *)backeView{
    if (!_backeView) {
        _backeView = [[UIView alloc]init];
        _backeView.backgroundColor = [UIColor whiteColor];
    }
    return _backeView;
}

- (UIButton *)cancleBtn{
    if (!_cancleBtn) {
        _cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancleBtn setTitleColor:KHEXCOLOR(@"#A5A5A5") forState:UIControlStateNormal];
        [_cancleBtn.titleLabel setFont:kMainFont(13)];
        [_cancleBtn addTarget:self action:@selector(cancleActive) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancleBtn;
}

- (UIButton *)sureBtn{
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sureBtn setTitle:@"确认" forState:UIControlStateNormal];
        [_sureBtn setTitleColor:KHEXCOLOR(@"#4795EF") forState:UIControlStateNormal];
        [_sureBtn.titleLabel setFont:kMainFont(13)];
        [_sureBtn addTarget:self action:@selector(sureActive:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureBtn;
}


- (UILabel *)addressLabel{
    if (!_addressLabel) {
        _addressLabel = [[UILabel alloc]init];
        [_addressLabel setFont:kFont(16)];
        [_addressLabel setTintColor:KHEXCOLOR(@"#262B2F")];
        _addressLabel.textAlignment = 1;
        _addressLabel.text = @"地区";
    }
    
    return _addressLabel;
}

- (UIView *)maskView{
    if (!_maskView) {
//        _maskView = [[UIView alloc]init];
//        _maskView.alpha = 0.5;
//        _maskView.backgroundColor = KHEXCOLOR(@"#000000");
        _maskView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-288.f)];
        _maskView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2f];
        // 设置子视图的大小随着父视图变化
        _maskView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _maskView.userInteractionEnabled = YES;
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancleActive)];
        tap.numberOfTouchesRequired = 1;
        tap.numberOfTapsRequired = 1;
        [_maskView addGestureRecognizer:tap];
    }
    return _maskView;
}

- (UIPickerView *)cityPickView{
    if (!_cityPickView) {
        _cityPickView = [[UIPickerView alloc]init];
        _cityPickView.delegate = self;
        _cityPickView.dataSource = self;
    }
    return _cityPickView;
}


/**
 * 懒加载plist
 *
 * @return plist对应的字典
 */
- (NSMutableArray*)cityNames
{
    if (!_cityNames) {
        
        //        NSString* path = [[NSBundle mainBundle] pathForResource:@"cities" ofType:@"plist"];
        //        _cityNames = [NSArray arrayWithContentsOfFile:path];
        _cityNames = [NSMutableArray array];
    }
    
    
    return _cityNames;
}

/**
 * 懒加载plist
 *
 * @return 省份
 */
- (NSMutableArray *)provinces{
    if (!_provinces) {
        
        _provinces = [NSMutableArray array];
    }
    return _provinces;
}


- (BRMutableDatePickerView *)datePickView{
    if (!_datePickView) {
        
        _datePickView = [[BRMutableDatePickerView alloc]init];
        _datePickView.selectDate = self.selectDate;
        _datePickView.hiddenDateUnit = YES;
        _datePickView.hiddenMonth = self.hiddenMonth;
        _datePickView.hiddenDay = self.hiddenDay;
        KWeakSelf;
        _datePickView.resultBlock = ^(NSDate *selectDate, NSString *selectValue, BOOL hiddenMonth, BOOL hiddenDay) {
            NSLog(@"选择的时间：%@", selectValue);
            weakSelf.selectDate = selectDate;
            weakSelf.hiddenMonth = hiddenMonth;
            weakSelf.hiddenDay = hiddenDay;
            weakSelf.maskView.hidden = YES;
        };
        


        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDate *currentDate = [NSDate date];
        NSDateComponents *comps = [[NSDateComponents alloc] init];
        [comps setYear:0];//设置最大时间为：当前时间推后0年
        NSDate *maxDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
        [comps setYear:-100];//设置最小时间为：当前时间前推100年
        NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];

        _datePickView.maxDate = maxDate;
        _datePickView.minDate = minDate;
     
    }
    return _datePickView;
}

- (NSMutableArray *)citysArr{
    if (!_citysArr) {
        _citysArr = [NSMutableArray array];
    }
    return _citysArr;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
